package com.docman.controller;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.docman.dao.DocumentDAO;
import com.docman.domainmodel.Constants;


@WebServlet("/DeleteFile")
public class DeleteFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public DeleteFileServlet() {
        super();
        
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	//TODO: use Try catch instead.
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("text/html;  charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		
		//Initializing file path both coming from the request and from constant class.
		String file = request.getParameter("link");
        String filePath = Constants.filePath+"\\"+file;
        //System.out.println("Delete file Servlete gelen path :" +file);
        File deleteFile = new File(filePath);
        
        boolean fileDeleteSuccess;
        boolean dbDeleteSuccess;
        if (!deleteFile.exists())
            throw new IllegalArgumentException(
                "Delete: no such file or directory: " + filePath);

          if (!deleteFile.canWrite())
            throw new IllegalArgumentException("Delete: write protected: "
                + filePath);
          
          fileDeleteSuccess  = deleteFile.delete();
          
          if (!fileDeleteSuccess)
              throw new IllegalArgumentException("Delete: deletion failed");
          //if both success than redirect the user to profile page.
          dbDeleteSuccess =DocumentDAO.deleteFile(filePath);
          
          if(dbDeleteSuccess && fileDeleteSuccess){
          response.sendRedirect("profileServletpath");
          }
	}

}
